<?php
/**
 * 系统参数设置
 * @by huanran.zhao
 * @2015-04-15
 */
class ConfigApp extends CommonApp{
	
	/**
	 * 首页
	 */
	public function indexAct(){
		$result = '';
		$alias = I('get.alias');
		if(!My::is_var($alias))
			$this->ajaxReturn(404,'alias参数有误！');
		$result = My::alias2detail('config',$alias);
		if(!is_array($result))//无数据时
			$this->ajaxReturn(404,'找不到配置数据！');
		//表单提交(修改)
		if($_POST){
			$id = My::arr2var($_POST,'id');
			if(!My::is_id($id))
				$this->ajaxReturn(404,'ID有误！');
			if(!My::arr2var($_POST,'params'))
				$this->ajaxReturn(404,'没有要修改的数据！');
			$data['params'] = My::arr2var($_POST,'params');
			$ok = DB('config')->where("`alias`='{$alias}' AND `id`={$id}")->clear()->save($data);
			if($ok)	$this->ajaxReturn(200,"编辑成功");
			else		$this->ajaxReturn(200,"编辑失败");
		}
		//正常页面显示
		else{
			$this->assign('result',$result);
			$this->display("Config/{$alias}");
		}
	}

	/**
	 * 配置中心文章列表
	 */
	public function listAct(){
		$result['page'] = My::page(DB('config')->cache()->count());
		$result['data'] = DB('config')->cache()->order("id DESC")->limit($result['page']['limits'])->select();
		$this->assign('result',$result);
		//display
		$this->display();
	}

	/**
	 * 编辑、保存
	 */
	public function modifyAct(){
		//保存表单
		if($_POST){
			$id = My::arr2var($_POST,'id');
			$alias = My::arr2var($_POST,'alias');
			if(!My::arr2var($_POST,'title'))
				$this->ajaxReturn(300,"标题不能为空！");
			if(!My::is_var($alias))
				$this->ajaxReturn(300,"alias唯一名称有误（必须是英文字符）");
			//编辑
			if(My::is_id($id)){
				$data['title'] = My::arr2var($_POST,'title');//只能编辑title字段
				$ok = DB('config')->where("`alias`='{$alias}' AND `id`={$id}")->clear()->save($data);
				if($ok)	$this->ajaxReturn(200,"编辑成功");
				else		$this->ajaxReturn(300,"编辑失败");
			}
			//添加
			else{
				if(DB('config')->where("`alias`='{$alias}'")->count()>0)
					$this->ajaxReturn(300,"alias唯一名称已经存在！");
				$data['title'] = My::arr2var($_POST,'title');
				$data['alias'] = $alias;
				$ok = DB('config')->clear()->add($data);
				if($ok)	$this->ajaxReturn(200,"添加成功");
				else		$this->ajaxReturn(300,"添加失败");
			}
		}
		//正常页面显示
		else{
			$result = '';
			$alias = I('get.alias');
			if(My::is_var($alias))
				$result = My::alias2detail('config',$alias);
			$this->assign('result',$result);
			$this->display();
		}
	}

}